package com.study.web;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;

/**
 * Created by IBM on 2016/4/28.
 */
@Controller
public class UserController {

    @RequestMapping("/formpage")
    public String formpage(){

        return "form";
    }
    @RequestMapping("/demo")
    public String demo(){

        return "demo";
    }
    @RequestMapping("/upload2")
    public void uploadXMLHttpRequest (
            HttpServletRequest request,
            HttpServletResponse response
    ) throws IOException{
        PrintWriter out = new PrintWriter(response.getOutputStream());
        FileItemFactory factory = new DiskFileItemFactory();// 为该请求创建一个DiskFileItemFactory对象，通过它来解析请求。执行解析后，所有的表单项目都保存在一个List中。
        ServletFileUpload upload = new ServletFileUpload(factory);
        List<FileItem> items;
        try {
            items = upload.parseRequest(request);
            Iterator<FileItem> itr = items.iterator();
            while (itr.hasNext()) {
                FileItem item = (FileItem) itr.next();
                System.out.println("是否是FormField: " + item.isFormField());
                System.out.println("接收到域: " + item.getFieldName());
                System.out.println("接收到值: " + item.getString("utf-8"));
                // 检查当前项目是普通表单项目还是上传文件。
                if (item.isFormField()) {// 如果是普通表单项目，显示表单内容。
                    String fieldName = item.getFieldName();
                    out.println("the field name is " + fieldName);// 显示表单域名称。
                } else {// 如果是上传文件，显示文件名。
                    out.println("the upload file name is " + item.getName());
                }
            }
            out.flush();
            out.close();
        } catch (FileUploadException e) {
            e.printStackTrace();
        }
    }
    @RequestMapping("/upload")
    @ResponseBody
    public String upload(
            String name,
            String extraField,
            @RequestParam(value="file",required=false) MultipartFile[] file,
            HttpServletRequest request
    ) throws IOException {
        //获得物理路径webapp所在路径
        String pathRoot = request.getSession().getServletContext().getRealPath("");
        String path="";
        List<String> listImagePath=new ArrayList<String>();
        for (MultipartFile mf : file) {
            if(!mf.isEmpty()){
                //生成uuid作为文件名称
                String uuid = UUID.randomUUID().toString().replaceAll("-","");
                //获得文件类型（可以判断如果不是图片，禁止上传）
                String contentType=mf.getContentType();
                //获得文件后缀名称
                String imageName=contentType.substring(contentType.indexOf("/")+1);
                path="D:/upload/"+uuid+"."+imageName;
                mf.transferTo(new File(path));
                listImagePath.add(path);
            }
        }
        System.out.println(path);
        request.setAttribute("imagesPathList", listImagePath);
        return "success";
    }
}
